package com.softdev.utils;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class DataUtils {

    /**
     * @description: 每页数量存在pageable中
     * @author: Jieyao Lu
     * @date: 2023/1/9  20:44
     * @param: [list, pageable]
     * @return: org.springframework.data.domain.Page<T>
     **/
    public static <T> Page<T> listToPage(List<T> list , Pageable pageable) {
        return  getPage(list , pageable);
    }

    /**
     * @description: 每页数量作为参数传入
     * @author: Jieyao Lu
     * @date: 2023/1/9  20:45
     * @param: [list, page, size]
     * @return: org.springframework.data.domain.Page<T>
     **/
    public static <T> Page<T> listToPage(List<T> list , int page , int size) {
        PageRequest pageable = PageRequest.of(page , size);
        return getPage(list , pageable);
    }

    public static <T> Page<T> getPage(List<T> list , Pageable pageable) {

        int pageStart = pageable.getPageNumber() * pageable.getPageSize();
        int expectPageEnd = pageStart + pageable.getPageSize() - 1;

        return Optional.of(list.size())
                .filter(size -> size >= pageStart)
                .map(size -> getRealSubList(pageStart , expectPageEnd , list , pageable))
                .orElseGet(() -> getEmptySubList(list , pageable));

    }

    public static <T> PageImpl<T> getRealSubList(int pageStart , int expcetPageEnd , List<T> list , Pageable pageable) {
        int realPageEnd = (list.size() > expcetPageEnd || list.size() == expcetPageEnd) ? expcetPageEnd + 1 : list.size();
        return new PageImpl<>(list.subList(pageStart , realPageEnd) , pageable , list.size());
    }

    public static <T> PageImpl<T> getEmptySubList(List<T> list , Pageable pageable) {
        return new PageImpl<>(new ArrayList<>() , pageable , list.size());
    }

}
